﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.ComponentModel;
using System.Net;

namespace for7raid.Control
{
    public class HTTPUtil
    {
        public static void GetLast128BytesAsync(string Url, Action<Stream> action)
        {
            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += (s, e) =>
                {
                    try
                    {
                        string url = e.Argument.ToString();
                        var request = WebRequest.Create(url) as HttpWebRequest;
                        request.Method = "HEAD";
                        var resp = request.GetResponse();
                        int ContentLength;
                        if (int.TryParse(resp.Headers.Get("Content-Length"), out ContentLength))
                        {

                            request = WebRequest.Create(url) as HttpWebRequest;
                            request.AddRange(ContentLength - 128, ContentLength);

                            e.Result = request.GetResponse().GetResponseStream();
                        }
                    }
                    catch (Exception)
                    {
                        
                        throw;
                    }
                };

            worker.RunWorkerCompleted += (s, e) =>
                {
                    if (e.Error == null)
                    {
                        var stream = e.Result as Stream;
                        action(stream);
                    }
                };

            worker.RunWorkerAsync(Url);
        }
    }
}
